package project.ccso.top.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import project.ccso.top.dao.impl.AdminDaoImpl;
import project.ccso.top.dao.impl.MemberDaoImpl;
import project.ccso.top.entity.Admin;
import project.ccso.top.entity.Member;

/**
 * 管理员登录拦截器，未登录之前禁止访问除主页、登录、注册以外的网页
 * @author aibinxiao
 * @date 2018年8月24日 下午1:26:03
 */
@WebFilter(filterName = "adminLoginFilter", urlPatterns = "/manager")
public class AdminLoginFilter implements Filter {

	public static Logger logger = LoggerFactory.getLogger(AdminLoginFilter.class);
    private AdminDaoImpl adminDao;
    private String loginPage = "/manager/login.html";
    private String[] excludePatterns = new String[] {"login.html", "AdminServlet"};
    private String[] excludeTypes = new String[] {"js","css","png","jpg","gif","jpeg","ico","do","txt"};

    // 取出url里文件名的那一段
    private static String url_reg_ex = "(((.*/)(.*)\\?)(.*))|((.*/)(.*))";
    private static Pattern pattern = Pattern.compile(url_reg_ex);

    /**
     * 获取url中的文件名
     * @param url
     * @return
     */
    private static String getPath(String url) {
        String path = "";
        Matcher matcher = pattern.matcher(url);
        if (matcher.find()) {
            path = matcher.group(4);
            if (path == null) {
                path = matcher.group(8);
            }
        }
        if (path == null) {
            path = "";
        }
        return path;
    }

    /**
     * 检查是否是不需要验证的url
     * @param url
     * @return
     */
    private boolean inExcludePatterns(String url) {
        boolean match = false;
        String path = getPath(url);
        if (this.excludePatterns != null && this.excludePatterns.length > 0) {
            for(String excludeUrl : this.excludePatterns) {
                if (excludeUrl.equals(path)) {
                    match = true;
                    break;
                }
            }
        }
        if (!match) {
            String type = null;
            if (path.contains(".")) {
                String[] parts = path.split("\\.");
                type = parts[parts.length - 1];
            }
            if (this.excludeTypes != null && this.excludeTypes.length > 0 && type != null) {
                for (String excludeType : this.excludeTypes) {
                    if (type.equals(excludeType)) {
                        match = true;
                        break;
                    }
                }
            }
        }
        return match;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("admin loginFilter start!");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        String url = request.getRequestURL().toString();
        if (this.inExcludePatterns(url)) { // 如果是不需要校验的url
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            HttpSession session = ((HttpServletRequest)servletRequest).getSession(true);
            Admin admin = (Admin)session.getAttribute("existAdmin");
            if (admin == null) {
                logger.debug("session has no admin !");

                // 需要检查一下cookie
                Cookie[] cookies = request.getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie cookie : cookies) {
                        if ("adminId".equals(cookie.getName())) {
                            String adminId = cookie.getValue();
                            admin = adminDao.findById(Integer.parseInt(adminId));
                            if (admin == null) {
                                Cookie newCookie =new Cookie("adminId", adminId);
                                newCookie.setMaxAge(0);
                                newCookie.setPath("/");
                                response.addCookie(cookie);
                            }
                            break;
                        }
                    }
                }

                // 如果还是没有用户信息，跳去登录页
                if (admin == null) {
                    logger.debug("no cookie found !");
                    ((HttpServletResponse)servletResponse).sendRedirect(((HttpServletRequest) servletRequest).getContextPath() + loginPage);
                    return;
                } else {
                    session.setAttribute("existAdmin", admin);
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }
    }

    @Override
    public void destroy() {
        logger.info("admin loginFilter end !");
    }

}
